package sdk.pay;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.InputStream;
import java.util.concurrent.atomic.AtomicInteger;

import sdk.pay.constant.PayExceptionType;
import sdk.pay.listener.Pay;
import sdk.pay.listener.PayGetPayStatusListener;
import sdk.pay.listener.PayUtilCallBack;
import sdk.pay.model.PayInfo;
import sdk.pay.utils.PayExceptionUtil;
import sdk.pay.utils.PayLogUtil;
import sdk.pay.utils.dynamic.PayDownloadUtil;
import sdk.pay.utils.dynamic.PayDynamicHelper;

import static android.app.AlertDialog.THEME_HOLO_LIGHT;
import static android.graphics.Color.BLACK;
import static android.graphics.Color.WHITE;
import static sdk.pay.PayHelper.TYPE_ALIPAY;
import static sdk.pay.PayHelper.TYPE_JDPAY;
import static sdk.pay.PayHelper.TYPE_QQPAY;
import static sdk.pay.PayHelper.TYPE_WECHAT;
import static sdk.pay.constant.PayExternalConstant.CONFIRM_PAY;
import static sdk.pay.constant.PayExternalConstant.FINISH_PAY;
import static sdk.pay.constant.PayExternalConstant.LOADING;
import static sdk.pay.constant.PayExternalConstant.OPEN_URL;
import static sdk.pay.constant.PayExternalConstant.PAY_STATUS;
import static sdk.pay.constant.PayExternalConstant.REQUEST_CODE;
import static sdk.pay.constant.PayExternalConstant.RESULT_CODE;
import static sdk.pay.constant.PayExternalConstant.TV_FINISH_PAY;
import static sdk.pay.constant.PayExternalConstant.TV_UN_FINISH_PAY;
import static sdk.pay.constant.PayExternalConstant.UN_FINISH_PAY;

/**
 * Created by lj on 2017/8/23 0023.
 */

public class PayExcessiveActivity extends Activity {
    private RelativeLayout mRelativeLayout;
    private Button mFinishPay;
    private Button mUnfinishPay;
    protected Dialog mProgressDialog;
    private static PayUtilCallBack mCallBack;
    private Pay mPay;
    private static PayInfo mPayInfo;
    private static boolean mPayStatusCallBack;
    private static Activity mActivity;
    private PayWebViewInterface mPayWebViewInterface;
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPay = PayDynamicHelper.getInstance().getPay();
        mPayWebViewInterface = PayDynamicHelper.getInstance().
                getPayWebViewInterface(mActivity, mPayInfo, mCallBack);
        if (null == mPayWebViewInterface || mPay == null) {
            PayDownloadUtil.getInstance().dateReset();
            PayExceptionUtil.getInstance().saveExceptionFile("can't get PayExcessiveActivity dynamic class!");
            throw new RuntimeException("can't get PayExcessiveActivity dynamic class!");
        }
        initView();
    }

    private void initView() {
        setTranslucent(true);
        mProgressDialog = ProgressDialog.show(this, "", LOADING, false, false, null);
        interfaceLayout();
        mUnfinishPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryStatus(false);
            }
        });
        mFinishPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryStatus(false);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPayInfo != null) {
            if (!mPayInfo.getIsPaying()) {
                selectPay();
            } else {
                queryStatus(true);
            }
        } else {
            PayLogUtil.logBase("mPayInfo: null");

        }

    }

    private void interfaceLayout() {
        final int blue = Color.rgb(72, 148, 232);
        final int gray = Color.rgb(153, 153, 153);
        mUnfinishPay = new Button(this);
        mFinishPay = new Button(this);
        mRelativeLayout = new RelativeLayout(getApplicationContext());
        mRelativeLayout.setId(generateViewId());
        mUnfinishPay.setId(generateViewId());
        mFinishPay.setId(generateViewId());
        mRelativeLayout.setBackgroundColor(WHITE);
        mUnfinishPay.setText(FINISH_PAY);
        mFinishPay.setText(UN_FINISH_PAY);
        mFinishPay.setTextColor(WHITE);
        mUnfinishPay.setTextColor(blue);
        mFinishPay.setBackgroundDrawable(drawRectangular(0, blue));
        mUnfinishPay.setBackgroundDrawable(drawRectangular(1, WHITE));
        ImageView imageView = new ImageView(this);
        imageView.setId(generateViewId());
        imageView.setBackgroundDrawable(loadImageFromAsserts(this, "image_icon_pay_excessive.png"));
        RelativeLayout.LayoutParams layteImageView = new RelativeLayout.LayoutParams(
                dip2px(100),
                dip2px(100)
        );
        layteImageView.setMargins(0, dip2px(115), 0, 0);
        layteImageView.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mRelativeLayout.addView(imageView, layteImageView);

        TextView tvFinishPay = new TextView(this);
        tvFinishPay.setId(generateViewId());
        tvFinishPay.setText(TV_FINISH_PAY);
        tvFinishPay.setTextSize(dip2px(5));
        tvFinishPay.setTextColor(gray);
        RelativeLayout.LayoutParams tvFinish = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        tvFinish.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tvFinish.setMargins(0, dip2px(45), 0, 0);
        tvFinish.addRule(RelativeLayout.BELOW, imageView.getId());
        mRelativeLayout.addView(tvFinishPay, tvFinish);

        TextView tvUnfinishPay = new TextView(this);
        tvUnfinishPay.setId(generateViewId());
        tvUnfinishPay.setText(TV_UN_FINISH_PAY);
        tvUnfinishPay.setTextSize(dip2px(5));
        tvUnfinishPay.setTextColor(gray);
        RelativeLayout.LayoutParams tvUnfinish = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        tvUnfinish.addRule(RelativeLayout.BELOW, tvFinishPay.getId());
        tvUnfinish.addRule(RelativeLayout.CENTER_HORIZONTAL);
        tvUnfinish.setMargins(0, dip2px(10), 0, 0);
        mRelativeLayout.addView(tvUnfinishPay, tvUnfinish);

        RelativeLayout.LayoutParams layteFinishPay = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                dip2px(40)
        );
        layteFinishPay.addRule(RelativeLayout.BELOW, tvUnfinishPay.getId());
        layteFinishPay.setMargins(dip2px(70), dip2px(40), 0, 0);
        layteFinishPay.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mRelativeLayout.addView(mFinishPay, layteFinishPay);

        RelativeLayout.LayoutParams layteUnfinishPay = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                dip2px(40)
        );
        layteUnfinishPay.setMargins(dip2px(70), dip2px(20), 0, 0);
        layteUnfinishPay.addRule(RelativeLayout.BELOW, mFinishPay.getId());
        layteUnfinishPay.addRule(RelativeLayout.CENTER_HORIZONTAL);
        mRelativeLayout.addView(mUnfinishPay, layteUnfinishPay);

        setContentView(mRelativeLayout);
    }

    private Drawable drawRectangular(int i, int color) {
        GradientDrawable mDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{color, color});
        mDrawable.setShape(GradientDrawable.RECTANGLE);
        mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
        mDrawable.setCornerRadii(new float[]{10, 10, 10, 10, 10, 10, 10, 10});
        if (i == 1) {
            mDrawable.setStroke(1, Color.rgb(72, 148, 232));
            return mDrawable;
        }
        return mDrawable;
    }

    //true auto search false
    private void queryStatus(final boolean flag) {
        if (!mPayStatusCallBack) {
            finish();
            return;
        }
        mProgressDialog = ProgressDialog.show(this, "", LOADING, false, true, null);
        mPay.getPayStatus(new PayGetPayStatusListener() {
            @Override
            public void onPayStatus(int payStatus) {
                dismiss();
                if (flag) {
                    if (payStatus == FAILURE) {
                        setTranslucent(false);
                    } else if (payStatus == ERROR) {
                        finish();
                    } else {
                        goBack(payStatus);
                    }
                } else {
                    goBack(payStatus);
                }
            }
        });
    }

    //true 透明  false 不透明
    private void setTranslucent(boolean flag) {
        Window window = getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); // 获取对话框当前的参数值
        if (flag) {
            windowLayoutParams.alpha = 0.0f;// 设置透明度
        } else {
            windowLayoutParams.alpha = 1.0f;// 设置透明度
        }
        getWindow().setAttributes(windowLayoutParams);
    }

    private void goBack(int payStatus) {
        Intent intent = new Intent();
        intent.putExtra(PAY_STATUS, payStatus);
        PayExcessiveActivity.this.setResult(RESULT_CODE, intent);
        finish();
    }

    private void selectPay() {
        String url = mPayInfo.getImgUrl();
        String openUrl = mPayInfo.getOpenUrl();
        String tokenId = mPayInfo.getPayToken();
        PayLogUtil.logBase("pay url = " + url + " openUrl = " + openUrl + " tokenId = " + tokenId);
        mPay.setPaying(true);
        PayLogUtil.logBase("selectPay: setPaying success");
        switch (mPayInfo.getPayTypeId()) {
            case TYPE_WECHAT:
                if (!TextUtils.isEmpty(url)) {
                    if (!TextUtils.isEmpty(openUrl) && OPEN_URL.equals(openUrl)) {
                        PayWebViewActivity.startActivity(PayExcessiveActivity.this, url);
                    } else {
                        if (TextUtils.isEmpty(url)) {
                            mPay.showToast(PayExceptionType.PAY_ERROR.getMessage());
                            return;
                        }
                        mPayWebViewInterface.loadUrl(url, false);
                    }
                }
                break;
            case TYPE_ALIPAY:
                if (!TextUtils.isEmpty(openUrl) && OPEN_URL.equals(openUrl)) {
                    PayWebViewActivity.startActivity(PayExcessiveActivity.this, url);
                } else {
                    if (TextUtils.isEmpty(url)) {
                        mPay.showToast(PayExceptionType.PAY_ERROR.getMessage());
                        return;
                    }
                    boolean isPilotRun = mPayInfo.getIsPilotRun();
                    mPayInfo.setIsPilotRun(false);
                    mPayWebViewInterface.loadUrl(url, isPilotRun);
                }
                break;
            case TYPE_QQPAY:
                if (!TextUtils.isEmpty(url)) {
                    if (!TextUtils.isEmpty(openUrl) && OPEN_URL.equals(openUrl)) {
                        PayWebViewActivity.startActivity(PayExcessiveActivity.this, url);
                    } else {
                        if (TextUtils.isEmpty(url)) {
                            mPay.showToast(PayExceptionType.PAY_ERROR.getMessage());
                            return;
                        }
                        mPayWebViewInterface.loadUrl(url, false);
                    }
                }
                break;
            case TYPE_JDPAY:
                if (!TextUtils.isEmpty(url)) {
                    if (!TextUtils.isEmpty(openUrl) && OPEN_URL.equals(openUrl)) {
                        PayWebViewActivity.startActivity(PayExcessiveActivity.this, url);
                    } else {
                        if (TextUtils.isEmpty(url)) {
                            mPay.showToast(PayExceptionType.PAY_ERROR.getMessage());
                            return;
                        }
                        PayBrowser payBrowser = new PayBrowser(PayExcessiveActivity.this);
                        payBrowser.doPay(url);
                    }
                }
                break;
            default:
                break;
        }
        mPayInfo.setPayTypeId(-1);
    }

    public static void startActivityForResult(Activity activity,
                                              PayInfo payInfo,
                                              PayUtilCallBack callBack,
                                              boolean payStatusCallBack) {
        mPayStatusCallBack = payStatusCallBack;
        mActivity = activity;
        mPayInfo = payInfo;
        mCallBack = callBack;
        Intent intent = new Intent(activity, PayExcessiveActivity.class);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPayInfo.setIsPaying(false);
        mPay.destroy();
        mPayWebViewInterface.clear();
        dismiss();
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismiss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showDialog() {
        TextView title = new TextView(this);
        title.setText(CONFIRM_PAY);
        title.setTextColor(BLACK);
        title.setPadding(10, 25, 10, 25);
        title.setGravity(Gravity.CENTER);
        title.setTextSize(20);
        new AlertDialog.Builder(this, THEME_HOLO_LIGHT)
                .setCustomTitle(title)
                .setCancelable(false)
                .setPositiveButton(FINISH_PAY, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        queryStatus(false);
                    }
                })
                .setNegativeButton(UN_FINISH_PAY, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        queryStatus(false);
                    }
                }).show();
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public int dip2px(float dpValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }

    private Drawable loadImageFromAsserts(final Context context, String fileName) {
        try {
            InputStream is = context.getResources().getAssets().open(fileName);
            return Drawable.createFromStream(is, null);
        } catch (OutOfMemoryError | Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
